<template>
    <div class="box">
      <div class="right" ref="right">
        <div class="rightContent" ref="rightContent">
          <div class="contentBox">
            <div class="periodWrap kline_periodWrap" ref="kline_periodWrap">
              <!-- DWM 分 -->
              <div class="btnGroup" style="position:relative" v-if="isTimeTab">
                <div
                  class="btn2"
                  v-for="(item, index) in KLinePeriodMenu"
                  :class="{ active: KLinePeriodIndex == index }"
                  :key="item.ID"
                  @click="OnClickKLinePeriodMenu(index, item, 'kline')"
                >
                  <span>{{ item.Name }}</span>
                </div>
                <div class="btn2" @click="isShow ? isShow = false : isShow = true">
                  <div class="btn2">
                    <img src="../../../assets/img/options.png" alt />
                  </div>
                </div>
                <div style="position:absolute;right: 0;top: 25px;;z-index: 99;" v-if="isShow == true">
                  <div
                    class="btnGroup"
                    v-show="IsShowRightMenu"
                    style="display: flex;flex-direction: column;"
                  >
                    <div
                      class="btn"
                      :class="{ active: KLineRightIndex == index }"
                      v-for="(item, index) in KLineRightMenu"
                      :key="item.ID"
                      style="padding:10px"
                      @click="OnClickKLineRightMenu(index, item)"
                    >{{ item.Name }}</div>
                    <div
                      class="btn"
                      v-for="(item) in KLineIndexMenu"
                      :key="item.ID"
                      style="padding:10px"
                      @click="ChangeKLineIndex(item)"
                    >{{ item.Name }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="hqchart" id="hqchart_minute" ref="kline" v-show="chartType == 'minute'"></div>
            <div class="hqchart" id="hqchart_kline" ref="kline2" v-show="chartType == 'kline'"></div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import _ from "lodash";
  import HQChart from "hqchart";
  import "hqchart/src/jscommon/umychart.resource/css/tools.css";
  import "hqchart/src/jscommon/umychart.resource/font/iconfont.css";
  import TrHQData from "../../../eastmoney/trHQData.js";
  import i18n from '@/locales/index.js'
  import { api } from '@/axios/api'
  
  HQChart.Chart.MARKET_SUFFIX_NAME.GetMarketStatus = function(symbol) {
    return 2;
  }; //一直交易
  
  function DefaultData() {}
  
  DefaultData.GetMinuteOption = function() {
    var option = {
      Type: "分钟走势图", //创建图形类型
  
      //窗口指标
      Windows: [
        // { Index:"KDJ", Modify: false, Change: true, Close: true},
      ],
  
      Symbol: "AAPL.usa",
      IsAutoUpdate: false, //是自动更新数据
      AutoUpdateFrequency: 20000,
      DayCount: 1, //1 最新交易日数据 >1 多日走势图
      IsShowRightMenu: false, //是否显示右键菜单
      CorssCursorTouchEnd: true,
  
      CorssCursorInfo: { Left: 1, Right: 1 },
  
      MinuteLine: {
        IsDrawAreaPrice: true, //是否画价格面积图
        IsShowAveragePrice: true //不显示均线
      },
  
      //边框
      Border: {
        Left: 1, //左边间距
        Right: 1, //右边间距
        Top: 0,
        Bottom: 1,
        AutoRight: { Blank: 10, MinWidth: 40 },
        AutoLeft: { Blank: 10, MinWidth: 40 }
      },
  
      //子框架设置
      // Height 是否显示成交量 柱状图 0 false
      Frame: [{ SplitCount: 5 }, { SplitCount: 3, Height: 0 }],
  
      //扩展图形
      ExtendChart: [
        //{Name:'MinuteTooltip' }  //手机端tooltip
      ]
    };
  
    return option;
  };
  
  DefaultData.GetMinuteIndexMenu = function() {
    var data = [
      { Name: "MACD", ID: "MACD", WindowIndex: 2 },
      { Name: "KDJ", ID: "KDJ", WindowIndex: 2 },
      { Name: "DMI", ID: "DMI", WindowIndex: 2 },
      { Name: "ROC", ID: "ROC", WindowIndex: 2 }
    ];
  
    return data;
  };
  
  DefaultData.GetKLineIndexMenu = function() {
    var data = [
      { Name: "MA", ID: "MA", WindowIndex: 0 },
      { Name: "BOLL", ID: "BOLL", WindowIndex: 0 },
      { Name: "MACD", ID: "MACD", WindowIndex: 1 },
      { Name: "KDJ", ID: "KDJ", WindowIndex: 1 },
      { Name: "DMI", ID: "DMI", WindowIndex: 1 },
      { Name: "ROC", ID: "ROC", WindowIndex: 1 }
    ];
  
    return data;
  };
  
  DefaultData.GetKLineOption = function() {
    var option = {
      Type: "历史K线图", //创建图形类型
  
      //窗口指标
      Windows: [
        { Index: "MA", Modify: true, Modify: false, Change: false, height: 20 },
        { Index: "ATR", Modify: false, Change: false, Close: false }
      ],
      Symbol: "600015.sh",
      IsAutoUpdate: false, //是自动更新数据
      AutoUpdateFrequency: 15000,
      IsApiPeriod: true,
      IsShowRightMenu: false, //是否显示右键菜单
  
      KLine: {
        DragMode: 1, //拖拽模式 0 禁止拖拽 1 数据拖拽 2 区间选择
        Right: 0, //复权 0 不复权 1 前复权 2 后复权
        Period: 0, //周期 0 日线 1 周线 2 月线 3 年线
        MaxReqeustDataCount: 1000, //数据个数
        PageSize: 60, //一屏显示多少数据
        KLineDoubleClick: false, //双击分钟走势图
        IsShowTooltip: true, //是否显示K线提示信息
        DrawType: 0,
        RightSpaceCount: 2
      },
  
      CorssCursorInfo: { Left: 0, Right: 1 },
  
      //标题设置
      KLineTitle: {
        IsShowName: false, //不显示股票名称
        IsShowSettingInfo: false, //不显示周期/复权
        isShowDateTime: true
      },
  
      //边框
      Border: {
        Left: 1, //左边间距
        Right: 1, //右边间距
        Top: 0,
        Bottom: 15,
        AutoRight: { Blank: 10, MinWidth: 40 }
      },
  
      //子框架设置
      Frame: [
        {
          SplitCount: 5,
          IsShowLeftText: false,
          IsShowYLine: false,
          Custom: [
            {
              Type: 0,
              Position: "right"
            }
          ],
          
        },
        { SplitCount: 3, IsShowLeftText: false },
        { SplitCount: 3, IsShowLeftText: false }
      ],
  
      //扩展图形
      ExtendChart: [
        //{ Name:'KLineTooltip' },  //手机端tooltip
      ]
    };
  
    return option;
  };
  
  DefaultData.GetMinuteDayMenu = function() {
    var data = [
      { Name: "1D", ID: 1 },
      { Name: "2D", ID: 2 },
      { Name: "3D", ID: 3 },
      { Name: "4D", ID: 4 },
      { Name: "5D", ID: 5 }
    ];
  
    return data;
  };
  
  DefaultData.GetKLinePeriodMenu = function() {
    var data = [
      { Name: i18n.t('hj86'), ID: 3 },
      { Name: i18n.t('hj87'), ID: 0 },
      { Name: i18n.t('hj88'), ID: 1 },
      { Name: i18n.t('hj89'), ID: 2 },
      { Name: i18n.t('hj90'), ID: 4 },
      { Name: i18n.t('hj91'), ID: 5 },
      { Name: i18n.t('hj92'), ID: 7 }
    ];
  
    return data;
  };
  
  DefaultData.GetKLineRightMenu = function() {
    var data = [
      { Name: i18n.t('hj93'), ID: 0 },
      { Name: i18n.t('hj94'), ID: 1 },
      { Name: i18n.t('hj95'), ID: 2 }
    ];
  
    return data;
  };
  
  export default {
    props:{
      hktype:{
        type:String,
        default:''
      }
    },
    data() {
      return {
        MinuteDayMenu: DefaultData.GetMinuteDayMenu(),
        MinuteDayIndex: 0,
        KLinePeriodMenu: DefaultData.GetKLinePeriodMenu(),
        KLinePeriodIndex: 1,
        KLineRightMenu: DefaultData.GetKLineRightMenu(),
        KLineRightIndex: 0,
        IsShowRightMenu: true,
        MinuteIndexMenu: DefaultData.GetMinuteIndexMenu(),
        KLineIndexMenu: DefaultData.GetKLineIndexMenu(),
  
        Symbol: "", 
  
        Chart: null, //图形控件  分时图
        KLineChart: null, //图形控件  K线图
  
        VolChartHeight: 10,
        chartType: "kline",
        isShow: false,
        isTimeTab: true,
      };
    },
    created() {
      const { query } = this.$route;
      
      // Default to a valid string format if query parameters are missing
      if (!query.code || !query.type) {
        console.warn('Missing required query parameters for Turkish stock');
        this.Symbol = "default_0.tur"; // Default symbol for Turkish stocks
      } else if (query.headertab == 1){
        this.Symbol = query.code;
      } else if(query.if_zhishu == "0") {
        this.Symbol = `${query.code}_${query.sok || '0'}.${query.type}`;
      } else if((query.code.indexOf('hk') > -1) && query.if_zhishu != 0){
        this.Symbol = `${query.if_zhishu || '0'}_${query.sok || '0'}.hk`;
      } else {
        this.Symbol = `${query.if_zhishu || '0'}_${query.sok || '0'}.${query.type}`;
      }
  
      // Ensure Symbol is a string
      if (typeof this.Symbol !== 'string') {
        console.warn('Symbol is not a string, converting to string');
        this.Symbol = String(this.Symbol);
      }
  
      console.log('Turkish Stock Symbol:', this.Symbol);
      //写入localStorage
      localStorage.setItem("hqchart_symbol", this.Symbol);
    },
    beforeDestroy(){
      clearInterval(window.timer)
      clearInterval(window.timer1)
      window.timer = null
      window.timer1 = null
    },
    mounted() {
      this.offHeight = this.$refs["rightContent"].offsetHeight;
      this.OnSize();
      this.SetChartStyle();
      this.$nextTick(() => {
        this.CreateMinuteChart();
        this.CreateKLineChart();
      });
      let that = this;
      window.onresize = _.debounce(this.OnSize, 200);
      // 自适应K线图
      var elementResizeDetectorMaker = require("element-resize-detector");
  
      // 创建实例，无参数
      var erd = elementResizeDetectorMaker(); //使用默认选项（将使用基于对象的方法）。
  
      // 创建实例带参数
      // 使用基于超快速滚动的方法。
      // 这是推荐的策略。
      var erdUltraFast = elementResizeDetectorMaker({
        strategy: "scroll",
        callOnAdd: true, //callOnAdd选项，用于确定在添加侦听器时是否应调用它们。默认为true。
        //如果为true，则确保在添加侦听器后将对其进行调用。如果为false，则在添加侦听器时将不保证其
        //被调用（不会阻止其被调用）
        debug: true
      });
      //监听class为staticNextMain的元素 大小变化
      var self = this;
      //侦听元素的调整大小事件，并使用元素作为调整大小事件的参数来调用侦听器函数。传递给函数的选项将
      //覆盖实例选项
      erd.listenTo(this.$refs["rightContent"], function(
        element
      ) {
        var width = element.offsetWidth;
        var height = element.offsetHeight;
        self.tableHeight = height - 100; //将监听到的宽高进行赋值
        self.tableWidth = width - 20;
        that.offHeight = height;
        that.OnSize();
      });
    },
  
    methods: {
      OnSize() {
        var width = this.$refs.right.clientWidth;
        var chartHeight = this.offHeight;
  
        var kline = this.$refs.kline;
        kline.style.width = width + "px";
        kline.style.height = chartHeight + "px";
        var kline2 = this.$refs.kline2;
        kline2.style.width = width + "px";
        kline2.style.height = chartHeight + "px";
  
        if (this.Chart) this.Chart.OnSize();
        if (this.KLineChart) this.KLineChart.OnSize();
      },
  
      changeRightContent(type) {
        this.KLinePeriodIndex = 0;
        this.chartType = type;
        this.$nextTick(() => {
          this.OnSize();
        });
      },
  
      SetChartStyle() {
        TrHQData.HQData.SetMinuteChartCoordinate();
        var blackStyle = HQChart.Chart.HQChartStyle.GetStyleConfig(
          HQChart.Chart.STYLE_TYPE_ID.WHITE_ID
        ); //读取黑色风格配置
        HQChart.Chart.JSChart.SetStyle(blackStyle);
      },
  
      CreateMinuteChart() {
        if (this.Chart) return;
  
        var option = DefaultData.GetMinuteOption();
        option.Symbol = this.Symbol;
        option.NetworkFilter = (data, callback) => {
          console.log(data, '----------------------');
          this.NetworkFilter(data, callback);
        }; //网络请求回调函数
  
        var chart = HQChart.Chart.JSChart.Init(this.$refs.kline);
        chart.SetOption(option);
        this.Chart = chart;
      },
  
      CreateKLineChart() {
        if (this.KLineChart) return;
  
        var option = DefaultData.GetKLineOption();
        option.Symbol = this.Symbol;
        option.NetworkFilter = (data, callback) => {
          console.log(data, '+++++++++++++++++++++');
          this.NetworkFilter(data, callback);
        }; //网络请求回调函数
  
        var chart = HQChart.Chart.JSChart.Init(this.$refs.kline2);
        HQChart.Chart.JSChart.GetResource().FrameLogo.Text = null;
        chart.SetOption(option);
        this.KLineChart = chart;
      },
  
      ChangeSymbol(symbol) {
        var symbolUpper = symbol.toUpperCase();
        var isShowVolChart = TrHQData.HQData.IsShowVolChart(symbolUpper);
        var frame = this.Chart.JSChartContainer.Frame.SubFrame[1];
        if (isShowVolChart) {
          if (frame.Height <= 0) frame.Height = this.VolChartHeight;
        } else {
          if (frame.Height > 0) this.VolChartHeight = frame.Height;
          frame.Height = 0;
        }
        var period = this.KLineChart.JSChartContainer.Period;
        var isShowRightMenu = TrHQData.HQData.IsEnableRight(period, symbol); //是否显示复权菜单
        this.IsShowRightMenu = isShowRightMenu;
  
        this.Symbol = symbol;
        this.Chart.ChangeSymbol(this.Symbol);
        this.KLineChart.ChangeSymbol(this.Symbol);
      },
  
      OnClickMinuteDayMenu(index, item) {
        this.MinuteDayIndex = index;
        this.Chart.ChangeDayCount(item.ID);
      },
  
      OnClickKLinePeriodMenu(index, item, type) {
          this.chartType = type;
          this.KLinePeriodIndex = index;
          console.log("ITEM.ID", item.ID);
          this.KLineChart.ChangePeriod(item.ID);
      },
  
      OnClickKLineRightMenu(index, item) {
        this.KLineRightIndex = index;
        this.KLineChart.ChangeRight(item.ID);
      },
  
      ChangeMinuteIndex(item) {
        if (this.Chart) this.Chart.ChangeIndex(item.WindowIndex, item.ID);
      },
  
      ChangeKLineIndex(item) {
        if (this.KLineChart)
          this.KLineChart.ChangeIndex(item.WindowIndex, item.ID);
      },
  
      NetworkFilter(data, callback) {
        try {
          TrHQData.HQData.Log("[TrHQChartDemo::NetworkFilter] data", data);
          
          // Ensure data.Request.Data.symbol is a string if it exists
          if (data.Request && data.Request.Data && data.Request.Data.symbol) {
            if (typeof data.Request.Data.symbol !== 'string') {
              console.warn('Symbol is not a string, converting to string');
              data.Request.Data.symbol = String(data.Request.Data.symbol);
            }
          }
    
          switch (data.Name) {
            //分时图数据对接
            case "MinuteChartContainer::RequestMinuteData":
              TrHQData.HQData.NetworkFilter(data, callback);
              break;
            case "MinuteChartContainer::RequestHistoryMinuteData":
              TrHQData.HQData.NetworkFilter(data, callback);
              break;
    
            case "KLineChartContainer::RequestHistoryData": //日线全量数据下载
              TrHQData.HQData.NetworkFilter(data, callback);
              break;
            case "KLineChartContainer::RequestRealtimeData": //日线实时数据更新
              TrHQData.HQData.NetworkFilter(data, callback);
              break;
            case "KLineChartContainer::RequestFlowCapitalData": //流通股本
              TrHQData.HQData.NetworkFilter(data, callback);
              break;
            case "KLineChartContainer::ReqeustHistoryMinuteData": //分钟全量数据下载
              TrHQData.HQData.NetworkFilter(data, callback);
              break;
            case "KLineChartContainer::RequestMinuteRealtimeData": //分钟增量数据更新
              TrHQData.HQData.NetworkFilter(data, callback);
              break;
          }
        } catch (error) {
          console.error("Error in NetworkFilter:", error);
          // Return empty data to prevent chart from crashing
          callback({ code: 0, stock: [] });
        }
      },
  
      handleSelect(key, keyPath) {
        console.log(key, keyPath);
        this.ChangeSymbol(keyPath[1]);
      },
  
      handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
  
      handleClose(key, keyPath) {
        console.log(key, keyPath);
      }
    }
  };
  </script>
  <style lang="less">
  @animation-duration: 0.3s;
  
  .box {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    background: none;
  
    .left,
    .right {
      top: 0;
    }
  
    .left {
      width: 240px;
      height: 100%;
      box-sizing: border-box;
      left: 0;
      overflow-x: auto;
  
      .el-menu {
        min-height: 100%;
  
        .el-submenu__title:hover {
          background-color: #363636 !important;
        }
  
        .el-menu-item:hover {
          background-color: #363636 !important;
        }
      }
    }
  
    .right {
      left: 240px;
      width: 100%;
      height: 100%;
      @rightTabHeight: 40px;
      display: flex;
      flex-direction: column;
  
      .rightTab {
        height: @rightTabHeight;
        width: 100%;
        background: #191919;
        border-bottom: 1px solid #000;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
  
        > .btn {
          cursor: pointer;
          width: 100%;
          text-align: center;
          color: #000;
  
          &:first-child {
            padding-right: 60px;
            text-align: right;
          }
  
          &:last-child {
            padding-left: 60px;
            text-align: left;
          }
  
          &:hover,
          &.active {
            color: rgb(2, 99, 226);
          }
        }
      }
  
      .rightContent {
        height: calc(100% - @rightTabHeight);
        width: 100%;
  
        .kline_periodWrap {
          display: flex;
          justify-content: space-between;
          background: #191919;
  
          .btnGroup:first-child {
            width: 60%;
          }
  
          .btnGroup:last-child {
            width: 100%;
          }
        }
      }
  
      .btnGroup {
        color: #000;
        display: flex;
        background: #fff;
  
        .btn {
          margin: 0 0.1rem;
          align-items: center;
          justify-content: center;
          color: #000;
          cursor: pointer;
  
          &:last-child {
            border-right: none;
          }
        }
        .active {
          color: rgb(2, 99, 226);
          font-weight: 800;
          background: rgb(245, 245, 245);
        }
      }
  
      #hqchart_minute {
        background-color: #fff;
        height: 5rem;
        position: relative;
      }
  
      #hqchart_kline {
        background-color: #fff;
        height: 5rem;
        position: relative;
      }
  
      .statementWrap {
        background: #191919;
        padding: 10px;
        font-size: 12px;
        color: #de432d;
        line-height: 20px;
        text-align: center;
      }
    }
  }
  
  .periodWrap {
    height: 0.7rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff !important;
  }
  .btnGroup {
    height: 100%;
    .bt2 {
      height: 100% !important;
      box-shadow: none !important;
      img {
        width: 0.5rem;
        height: 0.5rem;
      }
    }
  }
  .btn2 {
    width: 9.4%;
    display: flex;
    margin: 0 0.15rem;
    justify-content: center;
    align-items: center;
    border-radius: 0.15rem;
    img {
      width: 0.5rem;
      height: 0.5rem;
    }
    .active {
      color: rgb(2, 99, 226);
      font-weight: 800;
      background: rgb(245, 245, 245);
    }
  }
  canvas {
    height: 100% !important;
  }
  .hqchart {
    width: 100%;
    height: 7.5rem;
  }
  </style> 